<?php

namespace App\Http\Controllers\Admin;


// use App\Http\Controllers\Controller;
use App\Http\Forms\ExplosiveForm;
use App\Http\Forms\GiftForm;
use App\Http\Forms\PackageForm;
use App\Http\Forms\PackageLibForm;
use App\Http\Forms\RulesForm;
use App\Library\OSS;
use App\Modules\Comment\Models\Comment;
use App\Modules\Good\Models\Good;
use App\Modules\Good\Models\UserGoodsPoster;
use App\Modules\Order\Jobs\AddSpecJob;
use App\Modules\Package\Models\ExplosivePackage;
use App\Modules\Package\Models\Gift;
use App\Modules\Package\Models\GoodPackage;
use App\Modules\Package\Models\PackageAttr;
use App\Modules\Package\Models\PackageAttrValue;
use App\Modules\Package\Models\PackageSpec;
use App\Modules\Package\Models\UserPoster;
use App\Modules\Rebate\Models\RebateRule;
use App\Modules\Shop\GoodsList;
use App\Modules\Shop\Manager;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\User;
use Facade\Ignition\Support\Packagist\Package;
use http\Env\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Http\Forms\TagForm;
use App\Modules\System\Models\Tag;
use Illuminate\Support\Facades\Auth;
use App\Modules\User\Models\Admin;

class PackageController extends Controller
{
    public function index(Request $request)
    {
        $this->checkAuth("merchant_staff_goods_and_package", "package");
        $shopId = $request->input('shop_id');
        $name = $request->input('name');
        $category = $request->input('category');
        $id = $request->input('id');
        $query = GoodPackage::query()
            ->where('shop_id', $shopId)
            ->when(!is_null($category), function ($query) use ($category) {
                return $query->where('category', $category);
            })
            ->when(!is_null($id), function ($query) use ($id) {
                return $query->where('id', $id);
            })
            ->orderBy('status', 'desc')
            ->orderBy('sort', 'desc')
            ->orderBy('created_at', 'desc');

        if (!empty($name)) {
            $query->where('name', 'like', "%" . $name . "%");
        }
        $data = $query->paginate(20);
        $shop = Manager::getShop();
        if (!$category) {
            $category = $data[0]->category;
        }
        return view('package.index', compact('data', 'name', 'shop', 'shopId', 'category'));
    }

    public function create(Request $request)
    {
        $this->checkAuth("merchant_staff_and_package_add", "package-add");
        $shopId = $request->input('shop_id');
        $category = $request->input('category');
        $value = PackageAttrValue::query()->get()->groupBy('package_attr_id')->toArray();
        $attr = PackageAttr::query()
            ->whereIn('id', array_keys($value))
            ->get()->pluck('name', 'id')->all();
        $shop = Manager::getShop();
        $form = $this->form(PackageForm::class, [
            'method' => 'PUT',
            'url' => route('admin.package.store', ['shop_id' => $shopId, 'category' => $category]),
        ], [
            'package_attr' => $attr,
            'package_value' => $value,
            'shop' => $shop->pluck('name', 'id')->all(),
        ]);

        $flag = 'package';//用于区分表单页面的js
        return view('package.form', compact('form', 'shopId', 'category', 'flag'));
    }

    public function store(Request $request)
    {
        $this->checkAuth("merchant_staff_and_package_add", "package-add");
        $shopId = $request->input('shop_id');
        $category = $request->input('category');
        $form = $this->form(PackageForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        // TODO 测试代码
//        $data['cover'] = "";
//        $data['order_cover'] = "";
//        $data['hot_cover'] = "";
//        $data['recommend_cover'] = "";
//        $data['selected_cover'] = "";
//        $data['share_bg'] = "";
//        $data['virtual_sales_volume'] = "";
//        $data['share_bg'] = "";
//        $data['share_bg'] = "";

        $data['price'] = $data['price'] * 100;
        $data['display_price'] = $data['display_price'] * 100;
        $data['prepay'] = $data['prepay'] * 100;
        $data['is_free'] = $data['is_free'] ?? 0;
        $data['is_balance_pay'] = $data['is_balance_pay'] ?? 0;//是否可以使用充值消费
        $data['is_recharge'] = $data['is_recharge'] ?? 0;//本商品是否为充值商品
        $data['recharge_money'] = $data['is_recharge'] ? $data['recharge_money']*100 : 0;//实际充值金额

        if (!empty($data['discount_limit'])) {
            $data['discount_limit'] = $data['discount_limit'] * 100;
            $data['discount_amount'] = $data['discount_amount'] * 100;
        } else {
            $data['discount_limit'] = null;
            $data['discount_amount'] = null;
        }

        $valueIds = [];
        foreach ($data['service'] as $tmp) {
            $valueIds = array_merge($valueIds, array_column($tmp['value'], 'id'));
        }

        $attrValue = PackageAttrValue::query()->get()->keyBy('id');
        $service = [];
        foreach ($data['service'] as $tmp) {
            foreach ($tmp['value'] as $key1 => $tmp1) {
                $tmp['value'][$key1]['name'] = $attrValue->get($tmp1['id'])->value;
            }
            $service[] = $tmp;
        }
        $data['service'] = $service;
        $data['status'] = GoodPackage::STATUS_ON;
        $data['shop_id'] = $shopId;
        $data['category'] = $category;

        $data['tag_id'] = !empty($data['tag_id']) ? implode($data['tag_id'], ',') : '';

        /** @var GoodPackage $package */
        $package = GoodPackage::query()->create($data);
        foreach ($attrValue as $item) {
            PackageSpec::query()->create([
                "package_id" => $package->id,
                "attr_value_id" => $item->id,
                "sales_volume" => 0,
                "is_default" => in_array($item->id, $valueIds),
                "status" => GoodPackage::STATUS_ON,
            ]);
        }
        Shop::query()->find($data['shop_id'])->increment('goods_number');
        GoodsList::addData(GoodsList::TYPE_PACKAGE, $package->id, $package->price, $package->sort, $package->sales_volume ?? 0, $package->created_at, $package->visitor);
        return redirect()->route('admin.package.index', ['shop_id' => $shopId, 'category' => $category]);
    }

    public function edit($id)
    {
        $this->checkAuth("merchant_staff_and_package_edit", "package-edit");
        $package = GoodPackage::query()->find($id);
        $package->price /= 100;
        $package->display_price /= 100;
        $package->prepay /= 100;
        $package->discount_limit = is_null($package->discount_limit) ? null : $package->discount_limit / 100;
        $package->discount_amount = is_null($package->discount_amount) ? null : $package->discount_amount / 100;
        $package->recharge_money /= 100;
        $is_recharge = $package->is_recharge;

        $value = PackageAttrValue::query()->get()->groupBy('package_attr_id')->toArray();
        $attr = PackageAttr::query()
            ->whereIn('id', array_keys($value))
            ->get()->pluck('name', 'id')->all();
        $shop = Manager::getShop();
        $spec = PackageSpec::query()->where('package_id', $id)->get();
        $package->spec = $spec->pluck('attr_value_id')->all();

        $tagData = Tag::query()
                ->where('shop_id', $package->shop_id)
                ->get()
                ->pluck('name', 'id')
                ->all();
        $package->tag_id = !empty($package->tag_id) ? explode(',', $package->tag_id) : '';

        $form = $this->form(PackageForm::class, [
            'method' => 'POST',
            'url' => route('admin.package.update', ['id' => $package->id]),
            'model' => $package,
        ], [
            'package_attr' => $attr,
            'package_value' => $value,
            'shop' => $shop->pluck('name', 'id')->all(),
            'tag_id' => $tagData,
        ]);
//        $sidebar = 'index';
        $shopId = $package->shop_id;
        $category = $package->category;
        $flag = 'package';//用于区分表单页面的js
        return view('package.form', compact('form', 'shopId', 'category', 'is_recharge', 'flag'));
    }

    public function update($id)
    {
        $this->checkAuth("merchant_staff_and_package_edit", "package-edit");
        $form = $this->form(PackageForm::class);

        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();

        $data['price'] = $data['price'] * 100;
        $data['display_price'] = $data['display_price'] * 100;
        $data['prepay'] = $data['prepay'] * 100;
        $data['is_free'] = $data['is_free'] ?? 0;
        $data['is_balance_pay'] = $data['is_balance_pay'] ?? 0;//是否可以使用充值消费
        $data['is_recharge'] = $data['is_recharge'] ?? 0;//本商品是否为充值商品
        $data['recharge_money'] = $data['is_recharge'] ? $data['recharge_money']*100 : 0;//实际充值金额
        if (!empty($data['discount_limit'])) {
            $data['discount_limit'] = $data['discount_limit'] * 100;
            $data['discount_amount'] = $data['discount_amount'] * 100;
        } else {
            $data['discount_limit'] = null;
            $data['discount_amount'] = null;
        }

        $valueIds = [];
        foreach ($data['service'] as $tmp) {
            $valueIds = array_merge($valueIds, array_column($tmp['value'], 'id'));
        }

        $attrValue = PackageAttrValue::query()->get()->keyBy('id');
        $service = [];
        foreach ($data['service'] as $tmp) {
            foreach ($tmp['value'] as $key1 => $tmp1) {
                $tmp['value'][$key1]['name'] = $attrValue->get($tmp1['id'])->value;
            }
            $service[] = $tmp;
        }
        $data['service'] = $service;
        
        $data['tag_id'] = !empty($data['tag_id']) ? implode($data['tag_id'], ',') : '';

//        $spec = $data['spec'];
//        unset($data['spec']);
        $package = GoodPackage::query()
            ->where('id', $id)
            ->first();
        $package->update($data);
        PackageSpec::query()
            ->where('package_id', $id)
//            ->whereNotIn('attr_value_id', $valueIds)
            ->update([
                'is_default' => 0,
            ]);
        PackageSpec::query()
            ->where('package_id', $id)
            ->whereIn('attr_value_id', $valueIds)
            ->update([
                'is_default' => 1,
            ]);
//        $old = PackageSpec::query()->where('package_id', $id)->get()->pluck('attr_value_id')->all();

//        $del = array_diff($old, $spec);
//        $update = array_diff($spec, $del);
//        foreach ($del as $item) {
//            PackageSpec::query()
//                ->where('package_id', $id)
//                ->where('attr_value_id', $item)
//                ->delete();
//        }
//        foreach ($update as $item) {
//            PackageSpec::query()->updateOrCreate([
//                "package_id" => $id,
//                "attr_value_id" => $item,
//            ], [
//                "is_default" => in_array($item, $valueIds),
//                "status" => GoodPackage::STATUS_ON,
//            ]);
//        }
        UserPoster::query()->where('package_id', $id)->delete();
        GoodsList::query()->where('goods_type', GoodsList::TYPE_PACKAGE)->where('link_id', $id)->update(['sort' => $data['sort']]);
        return redirect()->route("admin.package.index", ['shop_id' => $package->shop_id, 'category' => $package->category]);
    }

//    public function editSpec($id)
//    {
//        $package = GoodPackage::query()->find($id);
//        $spec = PackageSpec::query()->where('package_id', $id)->get()->keyBy('attr_value_id');
//        $value = PackageAttrValue::query()
//            ->whereIn('id', $spec->pluck('attr_value_id')->all())
//            ->get();
//        $attr = PackageAttr::query()
//            ->whereIn('id', $value->pluck('package_attr_id')->all())
//            ->get();
//        $value = $value->groupBy('package_attr_id');
//        $sidebar = "index";
//        return view('package.spec', compact('package', 'spec', 'attr', 'value', 'sidebar'));
//    }
//
//    public function updateSpec($id, Request $request)
//    {
//        $package = GoodPackage::query()->find($id);
//        $data = $request->input('value');
//        foreach ($data as $key => $value) {
//            $premium = $value * 100;
//            PackageSpec::query()
//                ->where('id', $key)
//                ->update([
//                    'premium' => $value * 100,
//                    'price' => $package->price + $premium,
//                ]);
//        }
//        return redirect()->route('admin.package.index');
//    }

    public function changeSort(Request $request)
    {
        $this->checkAuth("merchant_staff_and_package_sort", "package");
        $id = $request->input('id');
        $sort = $request->input('sort');
        GoodPackage::query()
            ->where('id', $id)
            ->update(['sort' => $sort]);
        return null;
    }

    public function status($id)
    {
        // $this->checkAuth("merchant_staff_and_package_upper_and_lower", "package-upper_and_lower");
        $this->checkAuth(['merchant_staff_up','merchant_staff_down'], ['package_up', 'package_down']);

        $package = GoodPackage::query()->find($id);
        if ($package->status == GoodPackage::STATUS_ON) {
            $package->status = GoodPackage::STATUS_OFF;
            GoodsList::query()->where('goods_type', GoodsList::TYPE_PACKAGE)->where('link_id', $id)->delete();
        } else {
            $package->status = GoodPackage::STATUS_ON;
            GoodsList::addData(GoodsList::TYPE_PACKAGE, $package->id, $package->price, $package->sort, $package->sales_volume, $package->created_at, $package->visitor);
        }
        $package->save();
        return redirect()->back();
    }

    /**
     * 产品库
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function libList(Request $request)
    {
        $this->authorize('lib');
        $attr = $request->input('attr');
        $name = $request->input('name');
        $type = $request->input('type');
        $field = $request->input('field');
        $sort = $request->input('sort');

        $query = PackageAttrValue::query()
            ->where('package_attr_id', $attr)
            ->join('package_attrs', 'package_attrs.id', '=', 'package_attr_values.package_attr_id')
            ->select('package_attr_values.*', 'package_attrs.name');
        if (!empty($name)) {
            $query->where('value', 'like', '%' . $name . "%");
        }
        if (!empty($type)) {
            $query->where('name', 'like', '%' . $type . '%');
        }
        if (!empty($field)) {
            $query->orderBy($field, $sort);
        }
        $query
            ->orderBy('sort', 'desc')
            ->orderBy('created_at', 'desc');
        $value = $query->paginate(20);
        return view('package.lib', compact('name', 'type', 'field', 'sort', 'value', 'attr'));
    }

    public function changeLibSort(Request $request)
    {
        $id = $request->input('id');
        $sort = $request->input('sort');
        PackageAttrValue::query()
            ->where('id', $id)
            ->update(['sort' => $sort]);
        return null;
    }

    public function createLib(Request $request)
    {
        $this->authorize('lib-edit');
        $attr = $request->input('attr');
        $form = $this->form(PackageLibForm::class, [
            'method' => "PUT",
            'url' => route('admin.package.lib.store', ['attr' => $attr]),
        ]);
        $flag = 'package_lib';//用于区分表单页面的js
        $shopId = '';
        return view('package.form', compact('form', 'attr', 'flag', 'shopId'));
    }

    public function storeLib(Request $request)
    {
        $this->authorize('lib-edit');
        $attr = $request->input('attr');
        $form = $this->form(PackageLibForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $attrValue = PackageAttrValue::query()
            ->create([
                'package_attr_id' => $attr,
                'value' => $data['value'],
                'cover' => $data['cover'],
                'price' => $data['price'] * 100,
                'discount' => $data['discount'] ?? 100,
                'description' => $data['description'],
                'selling_price' => empty($data['discount']) ? $data['price'] : ($data['price'] * $data['discount']),
                'sort' => $data['sort'],
            ]);
        dispatch(new AddSpecJob($attrValue));
        return redirect()->route('admin.package.lib', ['attr' => $attr]);
    }

    public function editLib($id)
    {
        $this->authorize('package-edit');
        $attr = PackageAttr::query()->get();
        $value = PackageAttrValue::query()->where('id', $id)->first();
        $value->price /= 100;
        $form = $this->form(PackageLibForm::class, [
            'method' => "POST",
            'url' => route('admin.package.lib.update', ['id' => $id]),
            'model' => $value,
        ], [
            'attr' => $attr->pluck('name', 'id')->all(),
        ]);
        $attr = $value->package_attr_id;
        $flag = 'package_lib';
        $shopId = '';
        return view('package.form', compact('form', 'attr', 'flag', 'shopId'));
    }

    public function updateLib($id)
    {
        $this->authorize('lib-edit');
        $form = $this->form(PackageLibForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();

        $value = PackageAttrValue::query()
            ->where('id', $id)
            ->first();
        $value->update([
            'value' => $data['value'],
            'cover' => $data['cover'],
            'description' => $data['description'],
            'price' => $data['price'] * 100,
            'discount' => $data['discount'] ?? 100,
            'selling_price' => empty($data['discount']) ? $data['price'] : ($data['price'] * $data['discount']),
            'sort' => $data['sort'],
        ]);
        return redirect()->route('admin.package.lib', ['attr' => $value->package_attr_id]);
    }

    public function delLib($id)
    {
        $this->authorize('lib-edit');
        PackageAttrValue::query()
            ->where('id', $id)
            ->delete();
        return redirect()->back();
    }

    public function searchLib(Request $request)
    {
        $term = $request->input('term');
        $re = PackageAttrValue::query()
            ->where('value', 'like', "%" . $term . "%")
            ->get()
            ->pluck('value', 'id')
            ->all();
        return $re;
    }

    public function getComment(Request $request)
    {
        $this->checkAuth("merchant_staff_and_package_comment","good-comment");
        $shopId = $request->input('shop_id');
        $category = $request->input('category');
        $goods_id = $request->input('id');
        $comment = Comment::query()
                    ->where('type', Comment::TYPE_PACKAGE)
                    // ->where('link_id', $goods_id)
                    ->where('shop_id', $shopId)
                    ->orderBy('created_at', 'desc')
                    ->paginate(20);
        $user = User::query()
            ->whereIn('id', $comment->pluck('user_id')->all())
            ->get()
            ->keyBy('id');
        $image = [];

        // 商家回复
        $aCommentChild = Comment::query()
            ->whereIn('pid', $comment->pluck('id')->all())
            ->get(['id','pid','content', 'system_reply_username', 'merchant_reply_username'])
            ->keyBy('pid');

        $comment->map(function ($item) use ($aCommentChild) {
            if (!empty($item->image)) {
                if (gettype($item->image) == "string") {
                    $item->image = json_decode($item->image, true);
                }
                foreach ($item->image as $item1) {
                    $image[] = OSS::instance()->getUrl($item1);
                }
                $item->image = implode($image, ";");
            }
                
            $item->child = !empty($aCommentChild->get($item->id)) ? $aCommentChild->get($item->id) : '';

        });
        return view('package.comment', compact('comment', 'user', 'shopId', 'category'));
    }

    public function hideComment($id, $is_show)
    {
        $this->authorize('comment-edit');
        Comment::query()
            ->where('id', $id)
            ->where('type', Comment::TYPE_PACKAGE)
            ->update([
                'is_show' => $is_show,
            ]);
        return redirect()->back();
    }

    public function attrList()
    {
        $this->authorize('lib');
        $data = PackageAttr::query()
            ->orderBy('sort', 'desc')
            ->paginate(20);
        return view('package.attr', compact('data'));
    }

    public function storeAttr(Request $request)
    {
        $this->authorize('lib-attr-edit');
        $data = $request->input('attr');
        PackageAttr::query()
            ->create([
                'name' => $data,
            ]);
        return redirect()->back();
    }

    public function updateAttr($id, Request $request)
    {
        $this->authorize('lib-attr-edit');
        $data = $request->input('attr');
        PackageAttr::query()
            ->where('id', $id)
            ->update([
                'name' => $data,
            ]);
        return redirect()->back();
    }

    public function changeAttrSort(Request $request)
    {
        $id = $request->input('id');
        $sort = $request->input('sort');
        PackageAttr::query()
            ->where('id', $id)
            ->update(['sort' => $sort]);
        return null;
    }

    public function deleteAttr($id)
    {
        $this->authorize('lib-attr-edit');
        PackageAttr::query()
            ->where('id', $id)
            ->delete();
        PackageAttrValue::query()
            ->where('package_attr_id', $id)
            ->delete();
        return redirect()->back();
    }

    public function explosivePackageIndex()
    {
        $this->authorize('package-explosive');
        $data = ExplosivePackage::query()
            ->join('good_packages', 'good_packages.id', '=', 'explosive_packages.package_id')
            ->select('good_packages.name', 'explosive_packages.*')
            ->paginate(20);
        $sidebar = 'explosive';
        return view('package.explosive', compact('data', 'sidebar'));
    }

    public function createExplosivePackage()
    {
        $this->authorize('package-explosive-add');
        $form = $this->form(ExplosiveForm::class, [
            'url' => route('admin.package.explosive.store'),
            'method' => 'PUT',
        ]);
        $sidebar = 'explosive';
        $flag = 'explosive';
        $shopId = '';
        return view('package.form', compact('form', 'sidebar', 'flag', 'shopId'));
    }

    public function storeExplosivePackage()
    {
        $this->authorize('package-explosive-add');
        $form = $this->form(ExplosiveForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        ExplosivePackage::query()
            ->updateOrCreate([
                'package_id' => $data['package_id'],
            ], [
                'sort' => $data['sort'],
            ]);
        return redirect()->route('admin.package.explosive');
    }

    public function delExplosivePackage($id)
    {
        $this->authorize('package-explosive-remove');
        ExplosivePackage::query()
            ->where('id', $id)
            ->delete();
        return redirect()->back();
    }

    public function editRules($id, Request $request)
    {
        $this->authorize('package-rule');
        $package = GoodPackage::query()
            ->where('id', $id)
            ->first();
        $rules = RebateRule::query()
            ->where('type', RebateRule::TYPE_PACKAGE)
            ->where('link_id', $id)
            ->first();
        if (!is_null($rules)) {
            $rules->level1_rebate = $rules->level1_rebate / 100;
            $rules->level2_rebate = $rules->level2_rebate / 100;
            $rules->level3_rebate = $rules->level3_rebate / 100;
            $rules->level4_rebate = $rules->level4_rebate / 100;
            $rules->level_2_3_rebate = $rules->level_2_3_rebate / 100;
        }
        $shopId = $package->shop_id;
        $category = $package->category;

        $form = $this->form(RulesForm::class, [
            'method' => 'POST',
            'url' => route('admin.package.rules.update', ['id' => $id, 'shop_id' => $shopId, 'category' => $category]),
            'model' => $rules,
        ]);

        return view('package.form', compact('form', 'shopId', 'category'));
    }

    public function updateRules($id, Request $request)
    {
        $this->authorize('package-rule');
        $shopId = $request->input('shop_id');
        $category = $request->input('category');

        $form = $this->form(RulesForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['level1_rebate'] *= 100;
        $data['level2_rebate'] *= 100;
        $data['level3_rebate'] *= 100;
        $data['level4_rebate'] *= 100;
        $data['level_2_3_rebate'] *= 100;

        RebateRule::query()
            ->updateOrCreate([
                'type' => RebateRule::TYPE_PACKAGE,
                'link_id' => $id,
            ], $data);
        return redirect()->route('admin.package.index', ['shop_id' => $shopId, 'category' => $category]);
    }

    public function gift($id, Request $request)
    {
        $this->authorize('package-gift');
        $shopId = $request->input('shop_id');
        $category = $request->input('category');
        $data = Gift::query()
            ->where('package_id', $id)
            ->get()
            ->map(function ($item) {
                $content = "";
                foreach ($item->content as $value) {
                    $content .= $value['name'] . "<br />";
                }
                $item->content = $content;
                return $item;
            });
        $data->content = implode('\n', array_column($data->pluck('content')->all(), 'name'));
        return view('package.gift', compact('data', 'shopId', 'category', 'id'));
    }

    public function createGift($id, Request $request)
    {
//        $this->authorize('package-edit');
//        $shopId = $request->input('shop_id');
//        $category = $request->input('category');
//        $form = $this->form(GiftForm::class, [
//            'url' => route('admin.package.gift.store', ['id' => $id, 'shop_id' => $shopId, 'category' => $category]),
//            'method' => 'POST',
//        ]);
//        return view('package.form', compact('shopId', 'category', 'form'));
    }

    public function storeGift($id, Request $request)
    {
//        $this->authorize('package-gift');
//        $shopId = $request->input('shop_id');
//        $category = $request->input('category');
//        $this->authorize('package-explosive');
//        $form = $this->form(GiftForm::class);
//        if (!$form->isValid()) {
//            return redirect()->back()->withErrors($form->getErrors())->withInput();
//        }
//        $data = $form->getFieldValues();
//        $data['package_id'] = $id;
//        $data['content'] = PackageAttrValue::query()
//            ->whereIn('id', $data['content'])
//            ->get()
//            ->map(function ($item) {
//                return [
//                    'id' => $item->id,
//                    'name' => $item->value,
//                ];
//            });
//        Gift::query()
//            ->create($data);
//
//        return redirect()->route('admin.package.index', ['shop_id' => $shopId, 'category' => $category]);
    }

    public function destroyGift($id)
    {
//        Gift::query()->find($id)->delete();
//        return redirect()->back();
    }

    public function indexTag(Request $request)
    {
        $this->checkAuth('staff_tag', 'pkg_tag');
        $shopId = $request->input('shop_id');
        $name = $request->input('name', '');
        $data = Tag::query()
            ->when(!empty($name), function ($query) use ($name) {
                return $query->where('name', 'like', '%' . $name . "%");
            })
            ->where('shop_id', $shopId)
            ->orderBy('sort', 'desc')
            ->orderBy('created_at', 'desc')
            ->paginate(20);
        $shopData = Shop::query()->find($shopId);
        
        $category = 'tag';
        return view('package.index_tag', compact('data', 'shopId', 'category', 'name'));
    }

    public function createTag(Request $request)
    {
        $this->checkAuth('staff_tag-add', 'pkg_tag-add');

        $shopId = $request->input('shop_id');

        $shopData = Shop::query()->find($shopId);

        $form = $this->form(TagForm::class, [
            'url' => route('admin.package.tag.store', ['shop_id' => $shopId]),
            'method' => 'POST',
        ]);
        
        return view('package.form_tag', compact('form', 'shopId'));
    }

    public function storeTag(Request $request)
    {
        $this->checkAuth('staff_tag-add', 'pkg_tag-add');
        $shopId = $request->input('shop_id');
        $form = $this->form(TagForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['shop_id'] = $shopId;
        $data['admin_id'] = Auth::user()->id;

        Tag::query()->create($data);
        return redirect()->route('admin.package.tag', ['shop_id' => $data['shop_id']]);
    }

    public function editTag(Tag $tag, Request $request)
    {
        $this->checkAuth('staff_tag-edit', 'pkg_tag-edit');
        $shopId = $request->input('shop_id');

        $shopData = Shop::query()->find($shopId);
        
        $form = $this->form(TagForm::class, [
            'url' => route('admin.package.tag.update', ['tag' => $tag, 'shop_id' => $shopId]),
            'method' => 'PUT',
            'model' => $tag
        ]);
        return view('package.form_tag', compact('form', 'shopId'));
    }

    public function updateTag(Tag $tag, Request $request)
    {
        $this->checkAuth('staff_tag-edit', 'pkg_tag-edit');
        $shopId = $request->input('shop_id');
        $form = $this->form(TagForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['admin_id'] = Auth::user()->id;
        $tag->update($data);
        return redirect()->route('admin.package.tag', ['shop_id' => $shopId]);
    }

    public function destroyTag(Tag $tag)
    {
        $this->checkAuth('staff_tag-del', 'pkg_tag-del');
        $tag->delete();
        return redirect()->route('admin.package.tag', ['shop_id' => $tag->shop_id]);
    }

    public function changeSortTag(Request $request)
    {
        $id = $request->input('id');
        $sort = $request->input('sort');
        Tag::query()
            ->where('id', $id)
            ->update(['sort' => $sort]);
        return redirect()->back();
    }
}
